<template>
  <div class="order-payment-container">
    <!-- 头部导航 -->
    <div class="header">
      <van-nav-bar title="订单支付" left-text="返回" left-arrow @click-left="$router.back()"></van-nav-bar>
    </div>
    <!-- 订单信息不存在 -->
    <van-empty v-if="orderGoodsList.length === 0" image="error" description="订单信息不存在" />
    <div v-else>
      <!-- 订单信息 -->
      <div class="order-content">
        <div class="address-title" @click="show = true">收货地址</div>
        <!-- 收获地址 -->
        <div class="address">
          <van-cell is-link @click="show = true">
            <template #icon>
              <div class="icon">
                <van-icon name="location" />
              </div>
            </template>
            <template #title>
              <div class="address-content">
                <div class="address-detail">{{ address }}</div>
                <div class="name-phone">
                  <div class="name">{{ name }}</div>
                  <div class="phone">{{ phone }}</div>
                </div>
              </div>
            </template>
          </van-cell>
        </div>
      </div>
      <!-- 订单商品列表 -->
      <div class="order-goods-box">
        <div class="order-info">订单信息</div>
        <div class="goods-list">
          <GoodsItemCom :goods_info="orderGoodsList"></GoodsItemCom>
        </div>
      </div>
    </div>

    <!-- 选择地址 -->
    <van-popup v-model="show" position="bottom" round closeable>
      <SelectAddress
        @setChosenAddressId="
          (val) => {
            chosenAddressId = val
          }
        "
        @editUserInfo="setUserNamePhone"
      ></SelectAddress>
    </van-popup>
    <!-- 支付按钮 -->
    <div class="submit-btn">
      <van-button :loading="loading" loading-text="加载中..." block round color="linear-gradient(to right, #ff6034, #ee0a24)" @click="payment" :disabled="loading"> 立即支付 </van-button>
    </div>
  </div>
</template>

<script>
import SelectAddress from '@/components/user/order/SelectAddress.vue'
import GoodsItemCom from './GoodsItemCom.vue'
import axios from '@/utils/request/request'
import { Notify } from 'vant'
export default {
  name: 'orderPayment',
  data() {
    return {
      id: '',
      show: false,
      loading: false,
      orderGoodsList: [],
      show: false,
      chosenAddressId: '',
      address: '',
      name: '',
      phone: ''
    }
  },
  components: {
    SelectAddress,
    GoodsItemCom
  },
  methods: {
    async getOrderPayResult() {
      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      try {
        const data = await axios.get('/user/order/payment/result', {
          params: {
            orderId: this.id
          }
        })
        if (data.code === 200) {
          Notify({
            type: 'success',
            message: '支付成功！',
            duration: 1000,
            onClose: () => {
              this.$router.replace('/home')
            }
          })
        } else {
          this.getOrderContentById()
        }
      } catch (err) {
        Notify({
          type: 'danger',
          message: '获取订单支付结果失败！',
          duration: 1000
        })
      } finally {
        this.$toast.clear()
      }
    },
    setUserNamePhone({ addressDetail, name, tel }) {
      this.address = addressDetail
      this.name = name
      this.phone = tel
      this.show = false
    },
    // 根据id获取订单详情数据
    async getOrderContentById() {
      try {
        const data = await axios.get('/user/get/order/' + this.id, {
          params: {
            orderId: this.id
          }
        })
        if (data.code === 0) {
          // 获取成功，将数据进行保存
          this.address = data.data[0].address
          this.name = data.data[0].name
          this.phone = data.data[0].phone
          this.orderGoodsList = data.data.map((item) => {
            return {
              create_time: item.create_time,
              goods_count: item.goods_count,
              goods_id: item.goods_id,
              goods_img: item.goods_img,
              goods_name: item.goods_name,
              goods_price: item.goods_price,
              id: item.id,
              order_id: item.order_id,
              order_remark: item.order_remark
            }
          })
        } else if (data.code === 403 || data.msg === '身份验证失败！') {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 500,
            onClose: () => {
              localStorage.removeItem('user_token')
              this.$router.replace('/login')
            }
          })
        } else {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 500
          })
        }
      } catch (err) {
        Notify({
          type: 'danger',
          message: '获取订单数据失败！'
        })
      }
    },
    // 切换地址数据
    toggleAddress(item) {
      // item: 当前选中的地址信息
      this.addressList.forEach((val, index) => {
        if (val.id != item.id) {
          val.checked = false
        }
        if (index == this.addressList.length - 1) {
          item.checked = true
          this.show = false
        }
      })
    },
    // 发起支付请求
    async payment() {
      this.loading = true
      try {
        const data = await axios.post('/user/payment', {
          orderId: this.id,
          totalPrice: this.orderGoodsList.reduce((price, item) => {
            return (price += item.goods_count * item.goods_price)
          }, 0)
        })
        if (data.code === 0) {
          // 请求成功,打开支付宝支付
          window.location.href = data.data
        } else if (data.code === 403 || data.msg === '身份认证错误') {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 500,
            onClose: () => {
              localStorage.removeItem('user_token')
              this.$router.replace('/login')
            }
          })
        } else {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000
          })
        }
      } catch {
        Notify({ type: '支付请求失败！' })
      } finally {
        this.loading = false
      }
    }
  },
  async created() {
    this.id = this.$route.params.id
    this.getOrderPayResult()
  }
}
</script>

<style lang="less" scoped>
.order-payment-container {
  padding: 10px;
  padding-top: 46px;
  min-height: 100vh;
  padding-bottom: 70px;
  background-color: #f5f5f5;

  .header {
    position: fixed;
    top: 0;
    left: 0;
    height: 46px;
    border-bottom: 1px solid #f1f1f1;
    width: 100vw;
    z-index: 999;
  }

  .order-content {
    background-color: #fff;
    border-radius: 10px;
    margin-top: 10px;
    .address-title {
      font-size: 14px;
      font-weight: 600;
      color: #000;
      padding: 10px 20px;
    }

    .address {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 15px 10px;

      ::v-deep .van-cell {
        padding: 0;
        align-items: center;
      }

      .icon {
        color: #fff;
        background-image: linear-gradient(to right, #ff6034, #ee0a24);
        border-radius: 999px;
        padding: 0 5px;
        margin-right: 5px;
      }

      .address-content {
        .address-detail {
          color: #000;
          font-weight: 700;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 296px;
        }

        .name-phone {
          display: flex;
          align-items: center;

          .name {
            color: #323232;
            margin-right: 5px;
          }
          .phone {
            color: #777;
          }
        }
      }
    }
  }

  .order-goods-box {
    margin-top: 10px;
    background-color: #fff;
    border-radius: 10px;

    .order-info {
      padding: 10px;
      font-size: 14px;
      font-weight: 700;
      color: #000;
    }
  }

  .submit-btn {
    padding: 10px;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #fff;
  }
  ::v-deep .van-nav-bar .van-icon,
  ::v-deep .van-nav-bar__text {
    color: #323232;
  }

  ::v-deep .van-popup__close-icon {
    font-size: 16px;
  }
}
</style>
